<template>
    <LayOut :bread="[{
        title: '账单',
    }]">
        <template #functionalDomain>
            <el-space>
                <el-link type="primary" @click="goToNext('/bill/upload')">账单上传</el-link>
                <el-link type="primary" @click="goToNext('/bill/add')">新增账单</el-link>
            </el-space>
        </template>
        <el-form size="large">
            <el-row :gutter="20">
                <el-col :span="4">
                    <el-form-item label="类型" class="form-item">
                        <el-select v-model="formInline.type" placeholder="请选择收支类型" @change="onSubmit" clearable>
                            <el-option v-for="item in typeOpt" :key="item.value" :label="item.label" :value="item.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="平台" class="form-item">
                        <el-select v-model="formInline.paymentPlatform" placeholder="请选择平台" @change="onSubmit" clearable>
                            <el-option v-for="item in paltformOpt" :label="item.label" :value="item.value"
                                :key="item.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="交易类型" class="form-item">
                        <el-select v-model="formInline.transactionType" placeholder="请选择交易类型" @change="onSubmit" clearable>
                            <el-option v-for="item in transcation_classification_enum" :label="item.label"
                                :value="item.value" :key="item.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="标签" class="form-item">
                        <el-select v-model="formInline.tags" placeholder="请选择标签" @change="onSubmit" clearable>
                            <el-option v-for="item in options" :label="item.label" :value="item.value" :key="item.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="交易人" class="form-item">
                        <el-input v-model="formInline.trader" placeholder="请输入交易人" @input="onSubmit" clearable />
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="备注" class="form-item">
                        <el-input v-model="formInline.notes" placeholder="请输入备注" @input="onSubmit" clearable />
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="金额" class="form-item">
                        <el-input v-model.number="formInline.minMoney" type="number" placeholder="请输入要查询的最小金额"
                            @input="onSubmit" clearable />
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="id" class="form-item">
                        <el-input v-model="formInline.id" type="text" @input="onSubmit" placeholder="请输入要查询的 id"
                            clearable />
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="交易开始时间" class="form-item">
                        <el-date-picker v-model="formInline.startTime" type="date" placeholder="请选择交易开始时间" clearable
                            @change="startTimeChange" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="交易结束时间" class="form-item">
                        <el-date-picker v-model="formInline.endTime" type="date" placeholder="请选择交易结束时间" clearable
                            @change="endtTimeChange" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
                    </el-form-item>
                </el-col>
                <el-col :span="4" :offset="4">
                    <el-form-item class="form-item">
                        <div class="func">
                            <el-button type="primary" @click="onSubmit">查询</el-button>
                        </div>

                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <el-card>

            <el-table :data="tableData" style="width: 100%" :row-class-name="tableRowClassName"
                @sort-change="handleSortChange">
                <el-table-column prop="id" label="id" width="180">
                    <template #default="scope">
                        <el-link type="primary" :underline="false" target="_blank"
                            :href="`#/bill/detail?id=${scope.row.id}`">{{
                                scope.row.id }}</el-link>
                    </template>
                </el-table-column>
                <el-table-column prop="payTime" label="交易时间" sortable width="180" :formatter="formatPayTime" />
                <el-table-column prop="paymentPlatform" label="支付平台" width="180" :formatter="formatPaymentPlatform" />
                <el-table-column prop="type" label="收支" width="180" :formatter="formatType" />
                <el-table-column prop="transactionType" label="交易类型" width="180" :formatter="formatTransactionType" />
                <el-table-column prop="trader" label="交易人" width="180" />
                <el-table-column prop="tags" label="标签" width="180">
                    <template #default="scope">
                        <div v-if="scope.row.tags">
                            <el-space style="width: 100%;">
                                <el-tag type="primary" v-for="item in scope.row.tags.split(',')">{{ formatOptions(item)
                                }}</el-tag>
                            </el-space>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="transactionOrderNumber" label="交易订单号" width="180" />
                <el-table-column prop="paymentMethod" label="支付方式" width="180" />
                <el-table-column prop="money" label="金额" sortable width="180" />
                <el-table-column prop="notes" label="备注" width="180" />
                <el-table-column prop="merchantOrderNumber" label="商家订单号" width="180" />
                <el-table-column prop="tradingAccount" label="交易账户" />
            </el-table>
            <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="page" :page-sizes="[10, 20, 30, 40]" :page-size="limit"
                layout="slot, sizes, prev, pager, next, jumper" :total="total" default="共计">
                <template #default>
                    <span style="font-size: 15px; padding-right: 20px;">
                        总金额&nbsp;<span class="redText">{{ totalMoney }}</span>&nbsp;元,
                        共计&nbsp;<span class="redText">{{ total }}</span>&nbsp;笔
                    </span>
                </template>
            </el-pagination>
        </el-card>
    </LayOut>
</template>
<script lang="ts" setup>
import LayOut from '../components/LayOut.vue'
import { ref, reactive, onMounted } from 'vue'
import service from '../service/index'
import { to } from '../plugin/index'
import { ElLoading, ElMessage } from 'element-plus';
import type { IBillItemDataModal, IBillReqParamsModal } from '../type';
import dayjs from 'dayjs';
import { typeOpt, paltformOpt, transcation_classification_enum } from '../assets/ts'
import { useRouter } from 'vue-router';
const router = useRouter();

const { getBills, getTags } = service;

const formInline = reactive<IBillReqParamsModal>({})

let tableData = ref<IBillItemDataModal[]>([]);
let page = ref(1);
let limit = ref(10);
let total = ref(0);
let totalMoney = ref(0);
const options = ref<{ id: string, label: string, value: number }[]>([]);
let sortField = ref<string>('payTime');
let sort = ref<string>('DESC');

const tableRowClassName = ({
    row,
    rowIndex,
}: {
    row: IBillItemDataModal;
    rowIndex: number;
}) => {
    const money = parseFloat(row.money);
    if (money >= 100) {
        return 'warning-row'
    } else if (money >= 50) {
        return 'success-row'
    }
    return ''
}

const formatPayTime = (row, column, cellValue, index) => {
    return dayjs(cellValue).format('YYYY-MM-DD HH:mm:ss');
}

const formatPaymentPlatform = (row, column, cellValue, index) => {
    const item = paltformOpt.find(item => item.value === cellValue);
    if (item) {
        return item.label;
    }
    return cellValue;
}

const formatType = (row, column, cellValue, index) => {
    const item = typeOpt.find(item => item.value === cellValue);
    if (item) {
        return item.label;
    }
    return cellValue;
}

const formatTransactionType = (row, column, cellValue, index) => {
    const item = transcation_classification_enum.find(item => item.value === cellValue);
    if (item) {
        return item.label;
    }
    return cellValue;
}

const formatOptions = (cellValue: string) => {
    const item = options.value.find(item => item.value === Number(cellValue));
    if (item) {
        return item.label;
    }
    return cellValue;
}

const getBillsHandle = async () => {
    const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    const [res, err] = await to(getBills({ ...formInline, page: page.value, limit: limit.value, sortField: sortField.value, sort: sort.value }));
    loading.close();
    const result = res.data;
    if (!err && result.code === 0) {
        tableData.value = result.data.data;
        total.value = result.data.total;
        if (result.data.totalMoney) {
            totalMoney.value = result.data.totalMoney;
        } else {
            totalMoney.value = 0;
        }
    } else {
        ElMessage.error('获取账单列表数据失败');
        console.error(err);
    }
}

const getTagsHandle = async () => {
    const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    const [res, err] = await to(getTags());
    loading.close();
    const result = res.data;
    if (!err && result.code === 0) {
        console.log(result);
        options.value = result.data;
    } else {
        ElMessage.error('获取失败');
        console.error(err);
    }
}

const handleSortChange = ({ column, prop, order }) => {
    sortField.value = prop;
    if (order === 'ascending') {
        sort.value = 'ASC';
    } else {
        sort.value = 'DESC';
    }
    getTagsHandle();
    getBillsHandle();
}

const handleSizeChange = (value: number) => {
    limit.value = value;
    getBillsHandle();
}

const handleCurrentChange = (value: number) => {
    page.value = value;
    getBillsHandle();
}

const startTimeChange = (val: any) => {
    if (formInline.endTime && val > formInline.endTime) {
        formInline.startTime = '';
        return ElMessage.error('开始时间不能大于结束时间');
    }
    onSubmit();
}

const endtTimeChange = (val: any) => {
    if (formInline.startTime && val < formInline.startTime) {
        formInline.endTime = '';
        return ElMessage.error('结束时间不能小于开始时间');
    }
    onSubmit();
}

const onSubmit = () => {
    getTagsHandle();
    getBillsHandle();
}

const goToNext = (url: string) => {
    router.push(url);
}

onMounted(() => {
    getBillsHandle();
    getTagsHandle();
})
</script>
<style lang="less" scoped>
.el-form {
    margin-bottom: 40px;
}

.el-pagination {
    display: flex;
    justify-content: flex-end;
    padding: 40px 0;
}

.form-item {
    width: 100%;

    .func {
        width: 100%;
        display: flex;
        justify-content: flex-end;
    }

}

.redText {
    color: #FF6F61;
    font-weight: bold;
}

::v-deep(.warning-row) {
    --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

::v-deep(.success-row) {
    --el-table-tr-bg-color: var(--el-color-success-light-9);
}
</style>